package org.hry.netty.channelhandler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

import java.util.concurrent.TimeUnit;

public class MyIdleStateHandler extends ChannelDuplexHandler {

    private static ChannelHandlerContext context;

    static {
        System.out.println("开始调用自定义的超时策略");
        myTimeOut();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        if (ctx.channel().isActive()) {
            context = ctx;
        }
        super.channelRegistered(ctx);
    }


    private void myChannelIdle(ChannelHandlerContext ctx, MyIdleStateHandler evt) throws Exception {
        ctx.fireUserEventTriggered(evt);
    }

    /**
     * 这里就是模拟了 3 秒之后开始触发 fireUserEventTriggered
     * 当然你也可以根据流入进来的数据类型，或者其他的判断来控制 在什么时候调用 fireUserEventTriggered
     */
    private static void myTimeOut() {
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println("调用了 myTimeOut 方法");
                MyIdleStateHandler myIdleStateHandler = new MyIdleStateHandler();
                try {
                    myIdleStateHandler.myChannelIdle(context, myIdleStateHandler);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

}
